<?php

namespace admin\widgets;

use admin\assets\MarkdownAsset;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\widgets\InputWidget;

class MarkdownWidget extends InputWidget {

    public $editOptions = [];

    public function init() {
        parent::init();
        if (!isset($this->Setting['class'])) {
            $this->options['class'] = 'form-control';
        }
    }

    public function run() {
        $this->registerClientScript();

        if ($this->hasModel()) {
            $input = Html::activeTextarea($this->model, $this->attribute, $this->options);
        } else {
            $input = Html::textarea($this->name, $this->value, $this->options);
        }
        echo $input;
    }

    protected function registerClientScript() {
        $options = $this->defaults();

        $id = Html::getInputId($this->model, $this->attribute);
        $options = ArrayHelper::merge($options, $this->editOptions);
        $options = Json::htmlEncode($options);

        $view = $this->getView();
        MarkdownAsset::register($view);

        $view->registerJs("$('#{$id}').markdown({$options});");
    }

    private function defaults() {
        return [
            'autofocus' => FALSE,
            'height' => 350,
            'language' => 'zh',
        ];
    }

}